// pages/profile/healthInfo/healthInfo.js
Page({
  data: {
    // 用户基本信息
    userInfo: {
      name: '',
      gender: '男',
      age: 25,
      height: 170,
      weight: 60
    },
    
    // 健康指标数据
    healthMetrics: {
      bmi: 0,
      bmiStatus: '正常',
      bodyFatRate: 0, // 体脂率
      bloodPressure: {
        systolic: 0, // 收缩压
        diastolic: 0  // 舒张压
      },
      bloodSugar: {
        fasting: 0,   // 空腹血糖
        postprandial: 0 // 餐后血糖
      },
      lastUpdate: ''
    },
    
    // 健康风险评估
    healthRisks: {
      bmiRisk: '',
      bodyFatRisk: '',
      bloodPressureRisk: '',
      bloodSugarRisk: ''
    },
    
    // 表单数据
    formData: {
      bodyFatRate: '',
      systolicPressure: '',
      diastolicPressure: '',
      fastingSugar: '',
      postprandialSugar: ''
    },
    
    // 显示状态
    showEditForm: false,
    isEditing: false
  },

  onLoad() {
    this.loadUserData();
    this.calculateHealthMetrics();
  },

  onShow() {
    this.loadUserData();
    this.calculateHealthMetrics();
  },

  // 加载用户数据
  loadUserData() {
    const user = wx.getStorageSync('user') || {};
    const currentDate = new Date().toLocaleDateString();
    
    this.setData({
      'userInfo.name': user.name || '用户',
      'userInfo.gender': user.gender || '男',
      'userInfo.age': this.calculateAge(user.birthday) || 25,
      'userInfo.height': user.height || 170,
      'userInfo.weight': user.weight || 60,
      'healthMetrics.lastUpdate': currentDate
    });
  },

  // 计算年龄
  calculateAge(birthday) {
    if (!birthday) return 25;
    const birthDate = new Date(birthday);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    return age;
  },

  // 计算健康指标
  calculateHealthMetrics() {
    const { height, weight } = this.data.userInfo;
    const bmi = weight / Math.pow(height / 100, 2);
    
    // BMI状态判断
    let bmiStatus = '正常';
    if (bmi < 18.5) bmiStatus = '偏瘦';
    else if (bmi >= 18.5 && bmi < 24) bmiStatus = '正常';
    else if (bmi >= 24 && bmi < 28) bmiStatus = '偏胖';
    else bmiStatus = '肥胖';

    this.setData({
      'healthMetrics.bmi': bmi.toFixed(1),
      'healthMetrics.bmiStatus': bmiStatus
    });

    this.assessHealthRisks();
  },

  // 健康风险评估
  assessHealthRisks() {
    const { bmi, bodyFatRate, bloodPressure, bloodSugar } = this.data.healthMetrics;
    const risks = {};

    // BMI风险评估
    if (bmi < 18.5) {
      risks.bmiRisk = '体重偏轻，建议增加营养摄入';
    } else if (bmi >= 24) {
      risks.bmiRisk = '体重超标，建议控制饮食和增加运动';
    } else {
      risks.bmiRisk = '体重正常，保持健康生活方式';
    }

    // 体脂率风险评估
    if (bodyFatRate > 30) {
      risks.bodyFatRisk = '体脂率偏高，存在内脏脂肪堆积风险';
    } else if (bodyFatRate > 25) {
      risks.bodyFatRisk = '体脂率偏高，建议控制饮食';
    } else {
      risks.bodyFatRisk = '体脂率正常';
    }

    // 血压风险评估
    if (bloodPressure.systolic >= 140 || bloodPressure.diastolic >= 90) {
      risks.bloodPressureRisk = '血压偏高，存在心血管疾病风险';
    } else if (bloodPressure.systolic >= 120 || bloodPressure.diastolic >= 80) {
      risks.bloodPressureRisk = '血压偏高，建议注意饮食和运动';
    } else {
      risks.bloodPressureRisk = '血压正常';
    }

    // 血糖风险评估
    if (bloodSugar.fasting >= 7.0 || bloodSugar.postprandial >= 11.1) {
      risks.bloodSugarRisk = '血糖偏高，建议咨询医生';
    } else if (bloodSugar.fasting >= 6.1 || bloodSugar.postprandial >= 7.8) {
      risks.bloodSugarRisk = '血糖偏高，建议控制饮食';
    } else {
      risks.bloodSugarRisk = '血糖正常';
    }

    this.setData({
      healthRisks: risks
    });
  },

  // 编辑健康数据
  editHealthData() {
    this.setData({
      showEditForm: true,
      isEditing: true,
      'formData.bodyFatRate': this.data.healthMetrics.bodyFatRate || '',
      'formData.systolicPressure': this.data.healthMetrics.bloodPressure.systolic || '',
      'formData.diastolicPressure': this.data.healthMetrics.bloodPressure.diastolic || '',
      'formData.fastingSugar': this.data.healthMetrics.bloodSugar.fasting || '',
      'formData.postprandialSugar': this.data.healthMetrics.bloodSugar.postprandial || ''
    });
  },

  // 输入处理
  onBodyFatInput(e) {
    this.setData({ 'formData.bodyFatRate': e.detail.value });
  },

  onSystolicInput(e) {
    this.setData({ 'formData.systolicPressure': e.detail.value });
  },

  onDiastolicInput(e) {
    this.setData({ 'formData.diastolicPressure': e.detail.value });
  },

  onFastingSugarInput(e) {
    this.setData({ 'formData.fastingSugar': e.detail.value });
  },

  onPostprandialSugarInput(e) {
    this.setData({ 'formData.postprandialSugar': e.detail.value });
  },

  // 保存健康数据
  saveHealthData() {
    const { formData } = this.data;
    
    // 数据验证
    if (!this.validateHealthData(formData)) {
      return;
    }

    // 更新健康指标
    this.setData({
      'healthMetrics.bodyFatRate': parseFloat(formData.bodyFatRate) || 0,
      'healthMetrics.bloodPressure.systolic': parseFloat(formData.systolicPressure) || 0,
      'healthMetrics.bloodPressure.diastolic': parseFloat(formData.diastolicPressure) || 0,
      'healthMetrics.bloodSugar.fasting': parseFloat(formData.fastingSugar) || 0,
      'healthMetrics.bloodSugar.postprandial': parseFloat(formData.postprandialSugar) || 0,
      showEditForm: false,
      isEditing: false
    });

    // 重新评估健康风险
    this.assessHealthRisks();

    // 保存到本地存储
    this.saveToStorage();

    wx.showToast({
      title: '健康数据已保存',
      icon: 'success'
    });
  },

  // 数据验证
  validateHealthData(data) {
    if (data.bodyFatRate && (data.bodyFatRate < 0 || data.bodyFatRate > 50)) {
      wx.showToast({
        title: '体脂率应在0-50%之间',
        icon: 'none'
      });
      return false;
    }

    if (data.systolicPressure && (data.systolicPressure < 60 || data.systolicPressure > 250)) {
      wx.showToast({
        title: '收缩压应在60-250mmHg之间',
        icon: 'none'
      });
      return false;
    }

    if (data.diastolicPressure && (data.diastolicPressure < 40 || data.diastolicPressure > 150)) {
      wx.showToast({
        title: '舒张压应在40-150mmHg之间',
        icon: 'none'
      });
      return false;
    }

    if (data.fastingSugar && (data.fastingSugar < 2 || data.fastingSugar > 20)) {
      wx.showToast({
        title: '空腹血糖应在2-20mmol/L之间',
        icon: 'none'
      });
      return false;
    }

    if (data.postprandialSugar && (data.postprandialSugar < 2 || data.postprandialSugar > 30)) {
      wx.showToast({
        title: '餐后血糖应在2-30mmol/L之间',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 保存到本地存储
  saveToStorage() {
    const user = wx.getStorageSync('user') || {};
    user.healthMetrics = this.data.healthMetrics;
    wx.setStorageSync('user', user);
  },

  // 取消编辑
  cancelEdit() {
    this.setData({
      showEditForm: false,
      isEditing: false
    });
  },

  // 获取饮食建议
  getDietRecommendation() {
    const { healthMetrics, healthRisks } = this.data;
    
    // 构建推荐参数
    const recommendationParams = {
      bmi: healthMetrics.bmi,
      bmiStatus: healthMetrics.bmiStatus,
      bodyFatRate: healthMetrics.bodyFatRate,
      bloodPressure: healthMetrics.bloodPressure,
      bloodSugar: healthMetrics.bloodSugar,
      risks: healthRisks
    };

    // 跳转到推荐页面
    wx.navigateTo({
      url: `/pages/health/recommendation/recommendation?params=${encodeURIComponent(JSON.stringify(recommendationParams))}`
    });
  }
})